import Util from './utils'
import Session from './session'

const URL_CONFIG = {
  development: 'https://dev.ali-fc.mozigu.net/service/uniapp_base/session',
  production: 'https://api.ali-fc.moapp.net.cn/service/uniapp_base/session',
}

let loginPromise = null

const login = () => {
  if (!loginPromise) {
    const resolves = []
    const rejects = []

    loginPromise = new Promise((resolve, reject) => {
      resolves.push(resolve)
      rejects.push(reject)
    })

    _doLogin()
      .then(
        (res) => {
          resolves.forEach((resolve) => resolve(res))
        },
        (err) => {
          rejects.forEach((reject) => reject(err))
        },
      )
      .catch((err) => {
        rejects.forEach((reject) => reject(err))
      })
      .finally(() => {
        loginPromise = null
      })
  }

  return loginPromise
}

const _doLogin = () => {
  return new Promise((resolve, reject) => {
    const options = uni.getLaunchOptionsSync()

    if (options.scene === 1154) {
      resolve({})
      return
    }

    let storageData = Util.getStorageSession()
    if (storageData) {
      storageData = JSON.parse(storageData)
      storageData.create_time = storageData.create_time || 1

      // 默认缓存时间为24小时
      const ttl = 24 * 3600
      if (Date.now() / 1000.0 - storageData.create_time < ttl) {
        Session.updateSession(storageData)
        resolve(storageData)
      } else {
        _login().then(resolve, reject)
      }
    } else {
      _login().then(resolve, reject)
    }
  })
}

const _login = () => {
  return new Promise((resolve, reject) => {
    /* #ifdef H5 */
    _handleLoginResponse({}).then(resolve, reject)
    /* #endif */

    /* #ifdef MP */
    uni.login({
      success: (loginRes) => {
        _handleLoginResponse(loginRes).then(resolve, reject)
      },
      fail: (err) => {
        console.error('login failed:', err)
        // Util.reminderModal(err);
        reject(err)
      },
    })
    /* #endif */
  })
}

const _handleLoginResponse = (loginRes) => {
  return new Promise((resolve, reject) => {
    uni
      .request({
        url: URL_CONFIG.production,
        data: {
          appid: Session.getAppid(),
          platform: uni.getSystemInfoSync().uniPlatform,
          params: loginRes,
        },
        method: 'POST',
        timeout: 5000,
        header: {
          'content-type': 'application/json',
        },
      })
      .then((res) => {
        if (
          res.data.ret == 0 ||
          res.data.code == 0 ||
          `${res.data?.code?.toLowerCase()}` === 'ok' ||
          `${res.data?.code?.toLowerCase()}` === 'success'
        ) {
          Util.setStorageSession(res.data.data)
          Session.setSession(res.data.data)
          resolve(res.data.data)
        } else {
          reject(res.data)
        }
      })
      .catch((err) => {
        if (err?.errMsg?.includes('abort')) return
        Util.reminderModal(err)
        reject(err)
      })
  })
}

export default login
